package org.example.readwritelock;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.example.readwritelock.entity.Emp;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Objects;

/**
 * @author ZhengDp
 * @Date 2023/1/19 20:34
 */
@Slf4j(topic = "c.GenericDao")
public class GenericDao {

    private  JdbcTemplate jdbcTemplate;
    private  final String URL = "jdbc:mysql://localhost:3306/test";
    private  final String USERNAME = "root";
    private  final String PASSWORD = "Log3.1415926";

    public <T> T queryOne(Class<T> clazz,String sql , Object ... args) {
        log.info("查询数据库");
        JdbcTemplate template = getJdbcTemplate();
        return template.queryForObject(sql, new BeanPropertyRowMapper<>(clazz),args);
    }

    public <T> List<T> queryList(Class<T> clazz, String sql , Object... args) {
        log.info("查询数据库");
        return getJdbcTemplate().query(sql,new BeanPropertyRowMapper<>(clazz),args);
    }

    public void update(String sql,Object ... args) {
        log.info("操作数据库");
        getJdbcTemplate().update(sql,args);
    }


    private  JdbcTemplate getJdbcTemplate(){
        if(Objects.isNull(jdbcTemplate)) {

            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(URL);
            dataSource.setPassword(PASSWORD);
            dataSource.setUsername(USERNAME);
            jdbcTemplate = new JdbcTemplate(dataSource);
        }
        return jdbcTemplate;
    }

}
